<?php
namespace qgauth\datascope;
use Yii;

class RoleDataScopeService extends RoleDataScope
{
    public static function getListOfPage($params, $with = [])
    {
        $params = self::setParams($params);

        $models = self::find()->where($params)->with($with);

        $activeRecord = Yii::$app->esActiveRecordList->setModel($models)->setIsOpenMysqlExtendSearch(true)->setMySqlExtendSearchMethod('callMysqlSearch')->asArray(false)->setParams($params)->run();

        return [
            'models' => $activeRecord->getQuery(),
            'pages'  => $activeRecord->getPages()
        ];
    }

    /**
     * @param $query
     * @return void
     */
    public function callMysqlSearch($query)
    {
        if(!empty(self::$name))
        {
            $query->andFilterWhere(['LIKE', 'name', self::$name]);
        }

        if(self::$flag) $query->andWhere(['flag' => self::$flag]);

        if(self::$data_table) $query->andWhere(['data_table' => self::$data_table]);

        if(self::$data_field) $query->andWhere(['data_field' => self::$data_field]);

    }

    /**
     * 参数设置
     * @param $params
     * @param string $alias
     * @return mixed
     */
    public static function setParams($params, string $alias = '')
    {
        if(!empty($params))
        {

            if(isset($params['name']) && !empty($params['name']))
            {
                self::$name = $params['name'];
                unset($params['name']);
            }

            if(isset($params['flag']) && !empty($params['flag']))
            {
                self::$flag = (int)$params['flag'];
                unset($params['flag']);
            }

            if(isset($params['data_table']) && !empty($params['data_table']))
            {
                self::$data_table = (int)$params['data_table'];
                unset($params['data_table']);
            }

            if(isset($params['data_field']) && !empty($params['data_field']))
            {
                self::$data_field = (int)$params['data_field'];
                unset($params['data_field']);
            }

            if(!empty($alias))
            {
                $alias = "{$alias}.";

                foreach($params as $key => $value)
                {
                    if(isset($params[$key]))
                    {
                        $params[$alias . $key] = $params[$key];
                        unset($params[$key]);
                    }
                }
            }
        }
        return $params;
    }

    /**
     * 获取一条正常的数据
     * @return object
     */
    public static function getModels($id, $company_id, $with = [])
    {
        return self::find()->where(['id' => $id, 'company_id' => $company_id, 'is_delete' => self::IS_ONT_DELETE])->with($with)->one();
    }
}


